package com.hrbxlh.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;


/** 
 * http请求连接
 */ 
public class HttpConn {

	/** 
     * 请求不带JSON格式参数并返回JSON格式字符串 
     * 
     * @param getURL          url地址
     * @param requestMethod   请求方式          格式： "GET" 或  "POST"
     * @return String
     */ 
	public String httpConn (String getURL , String requestMethod) {
		HttpURLConnection httpURLConn = null;
		URL url;
		String back="";
		try {
			url = new URL(getURL);
			httpURLConn = (HttpURLConnection) url.openConnection();
			httpURLConn.setDoOutput(true);
			httpURLConn.setRequestMethod(requestMethod);
			httpURLConn.setRequestProperty("Content-Type","UTF-8");//设置字符集UTF-8			
			httpURLConn.setIfModifiedSince(999999999);
			httpURLConn.connect();			
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					httpURLConn.getInputStream(), "UTF-8"));// 设置编码,否则中文乱码
			String lines;
			while ((lines = reader.readLine()) != null) {
				back=back+lines;
			}
			reader.close();
			// 断开连接
			httpURLConn.disconnect();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		return back;		
	}
	
	/** 
     * 请求带JSON格式参数并返回JSON格式字符串
     * 
     * @param getURL          url地址
     * @param str             请求带的JSON格式的字符串
     * @return String
     */ 
	public String httpConnByStr (String getURL,String str) {
		HttpURLConnection httpURLConn = null;
		URL url;
		String back="";
		try {
			url = new URL(getURL);
			httpURLConn = (HttpURLConnection) url.openConnection();
			httpURLConn.setDoOutput(true);
			httpURLConn.setRequestMethod("POST");
			httpURLConn.setRequestProperty("Content-Type","UTF-8");//设置字符集UTF-8			
			httpURLConn.setIfModifiedSince(999999999);
			httpURLConn.connect();	
			
			DataOutputStream out = new DataOutputStream(httpURLConn.getOutputStream());	
			out.write(str.getBytes("UTF-8"));
			out.flush();
            out.close();
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					httpURLConn.getInputStream(), "UTF-8"));// 设置编码,否则中文乱码
			String lines;
			while ((lines = reader.readLine()) != null) {
				back=back+lines;
			}
			reader.close();
			// 断开连接
			httpURLConn.disconnect();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			back = null;
		}
		
		return back;		
	}
	
	
}
